package com.tancw.viewacty;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.tancw.utils.BitmapUtils;
import com.tancw.utils.CameraUtils;
import com.tancw.utils.FileUtils;
import com.tancw.utils.ImgUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class RegActivity extends AppCompatActivity {
    public static final int CHOOSE_PICTURE = 0;
    public static final int CHOOSE_CAMERA = 1;

    private GridView gridView;
    private Button btnSubmit;
    private Button btnBack;
    private Button btnImgChoose;
    private EditText etUser;
    private EditText etThing;
    private JSONObject pageObj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_index);
        gridView = findViewById(R.id.reg_grid);
        etUser = findViewById(R.id.user);
        etThing = findViewById(R.id.thing);
        btnSubmit = findViewById(R.id.btn_submit);
        btnBack = findViewById(R.id.btn_back);
        btnImgChoose = findViewById(R.id.btn_choose);
        pageObj = new JSONObject();

        btnSubmit.setOnClickListener((v) -> {
            saveInfo();
            goBack();
        });

        btnBack.setOnClickListener((v) -> {
            goBack();
        });

        btnImgChoose.setOnClickListener((v) -> {
            showChoosePicDialog();
        });
    }

    private void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("");
        String[] items = {"选择本地照片", "拍照"};
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE:
                        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image/*");
                        openAlbumIntent.putExtra("type", CHOOSE_PICTURE);
                        openAlbumIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        someActivityResultLauncher.launch(openAlbumIntent);
                        break;
                    case CHOOSE_CAMERA:
                        CameraUtils.openCameraForImage(RegActivity.this);
                        break;
                }
            }
        });
        builder.create().show();
    }

    private void goBack() {
        Intent intent = new Intent(RegActivity.this, MainActivity.class);
        startActivity(intent);
    }

    private void saveInfo() {
        String fileName = crtFileName();
        try {
            FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
            Toast.makeText(this, "保存成功", Toast.LENGTH_LONG).show();
            writer.write(getFileContent());
            writer.close();
            fos.close();
            Toast.makeText(this, "保存成功", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getFileContent() {
        try {
            pageObj.put("thing", etThing.getText().toString());
            pageObj.put("user", etUser.getText().toString());
            pageObj.put("time",getYearTime());
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return pageObj.toString();
    }

    private String crtFileName() {
        String thingVal = etThing.getText().toString();
        if (thingVal == null || thingVal.length() == 0) {
            throw new RuntimeException("请填写内容");
        }
        Log.d(">>", thingVal);
        String file = thingVal;
        if (file.length() > 15) {
            file = file.substring(0, 15);
        }
        return getNowTime() + "..." + file + ".txt";
    }

    private String getNowTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日HH时");
        return simpleDateFormat.format(new Date());
    }

    private String getYearTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date());
    }

    private ActivityResultLauncher<Intent> someActivityResultLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                    new ActivityResultCallback<ActivityResult>() {
                        @Override
                        public void onActivityResult(ActivityResult acty) {
                            Intent data = acty.getData();
                            ImgUtil util = new ImgUtil();
                            ClipData datas = data.getClipData();
                            if (data != null && datas != null) {
                                new Thread(()->{
                                    for (int i = 0; i < datas.getItemCount(); i++) {
                                        Uri itemUri = datas.getItemAt(i).getUri();
                                        util.addUri(itemUri);
                                        try {
                                            String name = FileUtils.crtName(itemUri.getPath());
                                            BitmapFactory.Options options = new BitmapFactory.Options();
                                            options.inPreferredConfig = Bitmap.Config.RGB_565;
                                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(itemUri), null, options);
                                            String ItemPath = BitmapUtils.saveBitmap(name, bitmap, RegActivity.this);
                                            util.addImg(ItemPath);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    try {
                                        pageObj.put("imgPaths", util.getImgsStr());
                                        loadGridView(util);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }).start();
                            } else {
                                Uri uri = data.getData();
                                Log.i("选择照片", uri.getAuthority());
                                new Thread(() -> {
                                    try {
                                        String name = FileUtils.crtName(uri.getPath());
                                        BitmapFactory.Options options = new BitmapFactory.Options();
                                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                                        String path = BitmapUtils.saveBitmap(name, bitmap, RegActivity.this);
                                        Log.i("图片", path);
                                        util.addImg(path);
                                        util.addUri(uri);
//                                        pageObj.put("imgPath", path);
                                        pageObj.put("imgPaths", util.getImgsStr());
                                        loadGridView(util);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }).start();
                            }
                        }
                    });

    private void loadGridView(ImgUtil util) {
        ImgAdapter adapter = new ImgAdapter(util.getUris());
        gridView.setAdapter(adapter);
    }

    class ImgAdapter extends BaseAdapter {

        private ArrayList<Uri> uris;

        public ImgAdapter(ArrayList<Uri> uris) {
            this.uris = uris;
        }

        @Override
        public int getCount() {
            return uris.size();
        }

        @Override
        public Object getItem(int position) {
            return uris.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(RegActivity.this, R.layout.griditem_addpic, null);
            ImageView imageView = view.findViewById(R.id.reg_img);
            imageView.setImageURI(uris.get(position));
            return view;
        }
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 表示 调用照相机拍照
            case CameraUtils.RequestCode.FLAG_REQUEST_CAMERA_IMAGE:
                if (resultCode == RESULT_OK) {
                    Bundle bundleData = data.getExtras();
                    Bitmap imageBitmap = (Bitmap) bundleData.get("data");
                    Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), imageBitmap, "IMG" + Calendar.getInstance().getTime(), null));
                    ImgUtil imgUtil = new ImgUtil();
                    imgUtil.addUri(uri);
                    String name = FileUtils.crtName(getRealPathFromURI(uri));
                    String path = null;
                    try {
                        path = BitmapUtils.saveBitmap(name, imageBitmap, this);
                        imgUtil.addImg(path);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    Log.i("相机", path);
                    try {
                        pageObj.put("imgPaths", imgUtil.getImgsStr());
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    loadGridView(imgUtil);
                }
        }
    }

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }
}
